package com.jfplugin.je;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.sleepycat.je.Database;
import com.sleepycat.je.Transaction;

public class BerkeleyDbKit {

	private static BerkeleyDbPro bdbPro = null;
	
	private static Map<String, BerkeleyDbPro> bdbProMap = new HashMap<String, BerkeleyDbPro>();

	/**
	 * 初始化
	 */
	static void init(){
		bdbPro = use(BerkeleyDbPlugin.DEFAULTCONFIGNAME);
	}
	
	/**
	 * 选择库
	 * @param configName
	 * @return
	 */
	static BerkeleyDbPro use(String configName){
		BerkeleyDbPro bdbPro = bdbProMap.get(configName);
		if(bdbPro == null){
			bdbPro = new BerkeleyDbPro(BerkeleyDbPlugin.bdbPluginMap.get(configName));
			bdbProMap.put(configName, bdbPro);
		}
		return bdbPro;
	}
	
	/**
	 * 开始事物 
	 * @return
	 */
	public static Transaction beginTransaction() {
		return bdbPro.beginTransaction();
	}

	/**
	 * 提交事务
	 * @param tx
	 */
	public static void commit(Transaction txn) {
		bdbPro.commit(txn);
	}

	/**
	 * 获取数据库
	 * @param dbName
	 * @return
	 */
	public static Database getDatabase(String dbName) {
		return bdbPro.getDatabase(dbName);
	}
	
	/**
	 * 删除
	 * @param dbName
	 * @param count
	 * @return
	 */
	public static boolean delete(String dbName, int count){
		return bdbPro.delete(dbName, count);
	}
	
	/**
	 * 获取指定条数
	 * @param dbName
	 * @param count
	 * @return
	 */
	public static List<KV> get(String dbName, int count) {
		return bdbPro.get(dbName, count);
	}

	/**
	 * 删除数据
	 * 
	 * @param dbName
	 * @param key
	 * @return
	 */
	public static boolean delete(String dbName, byte[] key) {
		return bdbPro.delete(dbName, key);
	}

	/**
	 * 获取数据
	 * 
	 * @param dbName
	 * @param key
	 * @return
	 */
	public static byte[] get(String dbName, byte[] key) {
		return bdbPro.get(dbName, key);
	}

	/**
	 * PUT数据
	 * 
	 * @param dbName
	 * @param key
	 * @param value
	 * @return
	 */
	public static boolean put(String dbName, byte[] key, byte[] value) {
		return bdbPro.put(dbName, key, value);
	}

	/**
	 * 
	 * @param dbName
	 * @param key
	 * @param binding
	 * @return
	 */
	public static Object get(String dbName, byte[] key , ObjectTupleBinding binding) {
		return bdbPro.get(dbName, key, binding);
	}
	
	/**
	 * 
	 * @param dbName
	 * @param key
	 * @param binding
	 * @return
	 */
	public static boolean put(String dbName , byte[] key , ObjectTupleBinding binding ){
		return bdbPro.put(dbName, key, binding);
	}
	
	/**
	 * PUT数据
	 * @param dbName
	 * @param kv
	 */
	public static void put(String dbName, KV kv) {
		bdbPro.put(dbName, kv);
	}
	
	/**
	 * 获取指定库的总条数
	 * 
	 * @param dbName
	 * @return
	 */
	public static long count(String dbName) {
		return bdbPro.count(dbName);
	}

	/**
	 * 关闭指定库
	 * 
	 * @param dbName
	 */
	public static void close(String dbName) {
		bdbPro.close(dbName);
	}

	/**
	 * 关闭全部库
	 */
	public static void closeAll() {
		bdbPro.closeAll();
	}
	
}
